import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import { User, AuthTokens, RegisterData } from '@/types'
import { authService } from '@/services/authService'
import userApi from '@/services/userApi'
import apiClient from '@/services/apiClient'
import toast from 'react-hot-toast'

interface AuthState {
  user: User | null
  tokens: AuthTokens | null
  isLoading: boolean
  isAuthenticated: boolean
  
  // Actions
  login: (username: string, password: string) => Promise<void>
  register: (data: RegisterData) => Promise<void>
  logout: () => void
  updateUser: (userData: Partial<User>) => void
  refreshToken: () => Promise<void>
  initializeAuth: () => void
  clearError: () => void
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      user: null,
      tokens: null,
      isLoading: false,
      isAuthenticated: false,

      login: async (username: string, password: string) => {
        try {
          console.log('🔐 [DEBUG] authStore.login() 开始:', { username })
          set({ isLoading: true })
          const response = await authService.login({ username, password })
          console.log('🔐 [DEBUG] authService.login() 响应:', response)
          
          set({
            user: response.user,
            tokens: response.tokens,
            isAuthenticated: true,
            isLoading: false,
          })

          // 设置全局 Authorization 头
          apiClient.defaults.headers.common['Authorization'] = `Bearer ${response.tokens.accessToken}`

          // 补充获取包含绑定关系的完整用户信息
          try {
            const me = await userApi.getMe()
            set({ user: { ...(me as any) } })
          } catch (e) {
            console.log('⚠️ [DEBUG] 拉取 /users/me 失败，稍后可重试', e)
          }
          
          console.log('✅ [DEBUG] authStore状态已更新:', { user: response.user, tokens: response.tokens, isAuthenticated: true })
          toast.success('登录成功！')
        } catch (error: any) {
          console.log('❌ [DEBUG] authStore.login() 失败:', error)
          set({ isLoading: false })
          const message = error.response?.data?.message || '登录失败，请重试'
          toast.error(message)
          throw error
        }
      },

      register: async (data: RegisterData) => {
        try {
          set({ isLoading: true })
          const response = await authService.register(data)
          
          set({
            user: response.user,
            tokens: response.tokens,
            isAuthenticated: true,
            isLoading: false,
          })

          // 设置全局 Authorization 头
          apiClient.defaults.headers.common['Authorization'] = `Bearer ${response.tokens.accessToken}`

          // 补充获取包含绑定关系的完整用户信息
          try {
            const me = await userApi.getMe()
            set({ user: { ...(me as any) } })
          } catch (e) {
            console.log('⚠️ [DEBUG] 拉取 /users/me 失败，稍后可重试', e)
          }
          
          toast.success('注册成功！')
        } catch (error: any) {
          set({ isLoading: false })
          const message = error.response?.data?.message || '注册失败，请重试'
          toast.error(message)
          throw error
        }
      },

      logout: () => {
        try {
          authService.logout()
        } catch (error) {
          console.error('Logout error:', error)
        } finally {
          set({
            user: null,
            tokens: null,
            isAuthenticated: false,
          })
          toast.success('已退出登录')
        }
      },

      updateUser: (userData: Partial<User>) => {
        const { user } = get()
        if (user) {
          set({
            user: { ...user, ...userData },
          })
        }
      },

      refreshToken: async () => {
        try {
          const { tokens } = get()
          if (!tokens?.refreshToken) {
            throw new Error('No refresh token available')
          }

          const response = await authService.refreshToken(tokens.refreshToken)

          // 兼容不同返回格式：优先使用 response.tokens.accessToken，其次 response.accessToken
          const newAccessToken = (response as any)?.tokens?.accessToken ?? (response as any)?.accessToken
          const newRefreshToken = (response as any)?.tokens?.refreshToken ?? tokens.refreshToken
          const nextUser = (response as any)?.user ?? get().user

          if (!newAccessToken) {
            throw new Error('No accessToken in refresh response')
          }

          // 更新 tokens 并标记为已认证
          set({
            tokens: { ...(tokens as any), accessToken: newAccessToken, refreshToken: newRefreshToken },
            user: nextUser,
            isAuthenticated: true,
          })

          // 设置全局 Authorization 头
          apiClient.defaults.headers.common['Authorization'] = `Bearer ${newAccessToken}`

          // 补充获取包含绑定关系的完整用户信息（失败忽略）
          try {
            const me = await userApi.getMe()
            set({ user: { ...(me as any) } })
          } catch (e) {
            console.log('⚠️ [DEBUG] 拉取 /users/me 失败，稍后可重试', e)
          }
        } catch (error) {
          console.error('Token refresh failed:', error)
          // 刷新失败，清除认证状态
          set({
            user: null,
            tokens: null,
            isAuthenticated: false,
            isLoading: false,
          })
          throw error
        }
      },

      initializeAuth: () => {
        console.log('🔄 [DEBUG] authStore.initializeAuth() 开始')
        // 刷新进入时先标记为加载中，避免守卫误判未登录
        set({ isLoading: true })
        const { tokens, user } = get()
        console.log('🔄 [DEBUG] 当前存储状态:', { hasTokens: !!tokens, hasUser: !!user, tokens, user })

        if (tokens?.accessToken) {
          // 跳过 /auth/verify，直接恢复登录态并设置全局 Authorization
          apiClient.defaults.headers.common['Authorization'] = `Bearer ${tokens.accessToken}`
          set({ isAuthenticated: true })

          // 尝试获取完整用户信息，失败则保留现有信息
          userApi.getMe()
            .then((me) => {
              set({ user: { ...(me as any) }, isLoading: false })
            })
            .catch((e) => {
              console.log('⚠️ [DEBUG] 初始化拉取 /users/me 失败，忽略', e)
              set({ isLoading: false })
            })
        } else {
          console.log('⚠️ [DEBUG] 没有存储的token，设置为未认证状态')
          set({
            user: null,
            tokens: null,
            isAuthenticated: false,
            isLoading: false,
          })
        }
      },

      clearError: () => {
        // 清除错误状态的方法，如果需要的话
      },
    }),
    {
      name: 'auth-storage',
      partialize: (state) => ({
        user: state.user,
        tokens: state.tokens,
        isAuthenticated: state.isAuthenticated,
      }),
    }
  )
)